package com.etrans.web.gps.business.report.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.etrans.egov.base.intf.TIntfObjTrack;
import com.etrans.web.gps.business.gis.domain.Track;
import com.etrans.web.gps.business.report.domain.OtherProvinceVeVO;
import com.etrans.web.gps.business.system.service.CommonService;
import com.etrans.web.gps.util.EgovUtil;
import com.etrans.web.gps.util.map.GpsToGaoDe;

/**
 * 问题车辆筛查Service
 * 
 * @author zhangw
 *
 */
@Service
public class OtherProvinceVeService extends CommonService {
	
	@Autowired
    private EgovUtil egovUtil;

//	/**
//	 * 设置最晚接收时间，用于判断车辆是否在线,单位（分钟）
//	 */
//	public static final Integer LAST_RVC_TIME = 60 * 24 * 7;

//	/**
//	 * 根据车牌号在轨迹表中查询车辆的最新的一系列轨迹
//	 * 
//	 */
//	public List<OtherProvinceVeVO> queryOtherVeLastTracksByNo(String vehicleNo) {
//		// 查询条件
//		HashMap<String, Object> whereMap = new HashMap<String, Object>();
//		whereMap.put("vehicle_no",vehicleNo);
//		// 加入排序条件sortMap,按照接收时间顺序排序
//		HashMap<String, Object> sortMap = new HashMap<String, Object>();
//		sortMap.put("rcv_time",-1);
//		List<OtherProvinceVeVO> velist = MGTemplete.find("egov", "gps_info_realtime_up", whereMap, sortMap,1,10, OtherProvinceVeVO.class);
//		return velist;
//	}
//
//	/**
//	 * 根据车牌号在轨迹表中查询车辆的最新的一条轨迹
//	 * 
//	 */
//	public OtherProvinceVeVO queryOtherVeLastTrackByNo(String vehicleNo) {
//		OtherProvinceVeVO vo = new OtherProvinceVeVO();
//		// 查询条件
//		HashMap<String, Object> whereMap = new HashMap<String, Object>();
//		whereMap.put("vehicle_no",vehicleNo);
//		// 加入排序条件sortMap,按照接收时间顺序排序
//		HashMap<String, Object> sortMap = new HashMap<String, Object>();
//		sortMap.put("rcv_time",-1);
//		List<OtherProvinceVeVO> velist = MGTemplete.find("egov", "gps_info_realtime_up", whereMap, sortMap,1,1, OtherProvinceVeVO.class);
//		if (velist != null && velist.size()>0) {
//			vo=velist.get(1);
//			return vo;
//		}
//		return null;
//	}
//	
//	/**
//	 * 根据时间查询范围时间内的所有存在轨迹的车辆
//	 * 
//	 */
//	public List<Object> queryOnLineVeCount(Date rvcTime) {
//		// 查询条件
//		HashMap<String, Object> whereMap = new HashMap<String, Object>();
//		HashMap<String, Object> where_rvcTime = new HashMap<String, Object>();
//		where_rvcTime.put("$gte", rvcTime);
//		whereMap.put("rcv_time", where_rvcTime);
//		String groupName = "vehicle_no";
//		List<Object> groupList = MGTemplete.groupBy("egov", "gps_info_realtime_up", whereMap, groupName, null, 0);
//		return groupList;
//	}

	/**
	 * 查询车辆总数和在线数
	 * @return
	 */
	public HashMap<String, Object> getAllOnlineCount() throws Exception {
		int allCount = 0;			//车辆总数
		int onlineCount = 0;		//在线车辆数
		HashMap<String, Object> result = new HashMap<String, Object>();
		List<OtherProvinceVeVO> allVehicleList = queryOtherProvinceVe(null);
		if(allVehicleList != null && allVehicleList.size() > 0){
			allCount = allVehicleList.size();
			List<String> onlineVehicleList = getOnlineVehicle(allVehicleList);
			if(onlineVehicleList != null && onlineVehicleList.size() > 0){
				onlineCount = onlineVehicleList.size();
			}
		}
		result.put("allCount", allCount);
		result.put("onlineCount", onlineCount);
		return result;
	}
	
	/**
	 * 获取定位树
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public HashMap<String, Object> getVehicleTreeJsonResult(String vehicle_no) throws Exception {
		//结果集
		HashMap<String, Object> result = new HashMap<String, Object>();
		// 监控树
		List<HashMap<String, Object>> nodeList = new ArrayList<HashMap<String, Object>>();
		int allCount = 0;			//车辆总数
		int onlineCount = 0;		//在线车辆数
		// 查询MySQL表的车辆
		List<OtherProvinceVeVO> allVehicleList = queryOtherProvinceVe(vehicle_no);
		if(allVehicleList != null && allVehicleList.size() > 0){
			allCount = allVehicleList.size();
			
			List<String> onlineVehicleList = getOnlineVehicle(allVehicleList);
			if(onlineVehicleList != null && onlineVehicleList.size() > 0){
				onlineCount = onlineVehicleList.size();
			}
			// 根节点
			HashMap<String, Object> root_node = new HashMap<String, Object>();
			root_node.put("ID", "-1");
			root_node.put("LEVEL", 1);
			root_node.put("open", true);		//默认展开
			root_node.put("nocheck", true);		//去掉根节点的选项框
			root_node.put("NAME", "外省车辆" + "(" + onlineCount + "/" + allCount + ")");
			nodeList.add(root_node);
			// 车辆节点
			for (OtherProvinceVeVO vehicle : allVehicleList) {
				HashMap<String, Object> vehicle_node = new HashMap<String, Object>();
				vehicle_node.put("ID", vehicle.getId());
				vehicle_node.put("PID", "-1");
				vehicle_node.put("LEVEL", 2);
				vehicle_node.put("VID", vehicle.getVehicle_no() + "_" + vehicle.getVehicle_color());
				vehicle_node.put("NAME", vehicle.getVehicle_no() + "(" + vehicle.getVehicle_color_name() + ")");
				nodeList.add(vehicle_node);
			}
		}else{
			// 根节点
			HashMap<String, Object> root_node = new HashMap<String, Object>();
			root_node.put("ID", "-1");
			root_node.put("LEVEL", 1);
			root_node.put("open", true);		//默认展开
			root_node.put("isParent", true);	//默认为根节点
			root_node.put("nocheck", true);		//去掉根节点的选项框
			root_node.put("NAME", "外省车辆" + "(0/0)");
			nodeList.add(root_node);
		}
		result.put("nodeList", nodeList);
		return result;
	}
	
	/**
     * 获取在线车辆
     * @param vehicles 车辆集
     * @throws Exception
     */
    public List<String> getOnlineVehicle(List<OtherProvinceVeVO> vehicles) throws Exception {
    	if(vehicles != null && vehicles.size() > 0){
    		String[] vehicleArray = new String[vehicles.size()];
    		for (int i = 0; i < vehicles.size(); i++) {
    			String vehicle_no = String.valueOf(vehicles.get(i).getVehicle_no());
    			String vehicle_color = String.valueOf(vehicles.get(i).getVehicle_color());
    			//车牌号_车牌颜色添加到数组
    			vehicleArray[i] = String.format("%s_%s", vehicle_no, vehicle_color);
    		}
    		//获取车辆上下线状态（如果不存在最后一条轨迹，不会返回）
    		Map<String,List<String>> vehicleStatus = egovUtil.getVehicleStatusUp(vehicleArray);
    		//获取上线车辆集合
    		return vehicleStatus.get("online");
    	}
		return null;
    }
    
	/**
     * 根据车牌号_车牌颜色，从服务端获取定位数据
     * @return
     * @throws Exception
     */
    public List<Track> getSubScribe(String[] vehicle_no_color) throws Exception {
        List<Track> result = new ArrayList<Track>();
        List<TIntfObjTrack> resTrack = egovUtil.getTrackUp(vehicle_no_color);
        for (TIntfObjTrack objTrack : resTrack) {
            if (objTrack != null) {
                Track track = new Track();
                track.setVehicleNo(objTrack.getVehicleNo());
                track.setVehicleColor(objTrack.getVehicleColor());
                track.setVehicleId(objTrack.getVehicleId());
                track.setLongitudeD(objTrack.getLongitudeD());
                track.setLatitudeD(objTrack.getLatitudeD());
                if (objTrack.getValid()) {
                    track.setValidS("定位");
                } else {
                    track.setValidS("盲区");
                }
                if (objTrack.getLatitudeD() != 0 && objTrack.getLongitudeD() != 0) {
                    double[] gdLatlon = GpsToGaoDe.transform(objTrack.getLatitudeD(), objTrack.getLongitudeD());
                    track.setLatitude(gdLatlon[0]);
                    track.setLongitude(gdLatlon[1]);
                }
                track.setGpsTimeS(objTrack.getGpsTimeS());
                track.setGpsMileage(objTrack.getMileage());
                track.setGpsSpeedF(objTrack.getGpsSpeed());
                track.setPulseSpeedF(objTrack.getPulseSpeed());
                track.setHead(objTrack.getDirection());
                track.setValid(objTrack.getValid());
                track.setAccStatus(objTrack.getAccON());
                if (objTrack != null && objTrack.getGpsTimeS() != null) {   // 1.开车 2 停车  3离线       4 报警(去掉)
                    long diff = System.currentTimeMillis() - objTrack.getGpsTime();
                    if (Math.abs(diff) < 1000 * 60 * 10) {
                        if (objTrack.getGpsSpeed() > 0) {
                            track.setCarStatus(1);
                        } else {
                            track.setCarStatus(2);
                        }
                    } else {
                        track.setCarStatus(3);
                    }
                }
                result.add(track);
            }
        }
        return result;
    }

	/**
	 * 查询所有省外车辆
	 * 
	 */
	public List<OtherProvinceVeVO> queryOtherProvinceVe(String vehicle_no) {
		HashMap<String,Object> param = new HashMap<String, Object>();
		param.put("vehicle_no", vehicle_no);
		return selectList("otherProviceVeQuery.queryOtherProvinceVe", param);
	}

	/**
	 * 获取菜单名称
	 * 
	 */
	public String getMenuNameById(Integer menuId) {
		return selectOne("otherProviceVeQuery.getMenuNameById", menuId);
	}

//	/**
//	 * 根据车牌号查询外省车辆
//	 * @return 车辆信息和在线状态
//	 */
//	public List<OtherProvinceVeVO> queryOtherProVeByNo(String vehicle_no) {
//		List<OtherProvinceVeVO> resultList = new ArrayList<OtherProvinceVeVO>();
//		//在数据库中查找车辆
//		HashMap<String,String> paramMap = new HashMap<String,String>();
//		paramMap.put("vehicle_no", vehicle_no);
//		List<OtherProvinceVeVO> otherProVeList = selectList("otherProviceVeQuery.queryOtherProvinceVe",paramMap);
//		if (otherProVeList != null && otherProVeList.size() > 0) {
//			for (OtherProvinceVeVO otherProVe : otherProVeList) {
//				Integer id = otherProVe.getId();
//				String veColorName = otherProVe.getVehicle_color_name();
//				//查找实时轨迹
//				OtherProvinceVeVO otherProVeTrack = queryOtherVeLastTrackByNo(otherProVe.getVehicle_no());
//				if (otherProVeTrack != null) {
//					Date lastRcvTime = otherProVeTrack.getRcv_time();
//					if (System.currentTimeMillis() - lastRcvTime.getTime() > LAST_RVC_TIME * 60 * 1000) {
//						//在线
//						otherProVeTrack.setIsOnLine(1);
//						otherProVeTrack.setId(id);
//						otherProVeTrack.setVeColorName(veColorName);
//						resultList.add(otherProVeTrack);
//					}else {
//						//离线
//						otherProVeTrack.setId(id);
//						otherProVeTrack.setVeColorName(veColorName);
//						otherProVeTrack.setIsOnLine(0);
//						resultList.add(otherProVeTrack);
//					}
//				}else {
//					otherProVe.setIsOnLine(0);
//					resultList.add(otherProVe);
//				}
//			}
//		}
//		return resultList;
//	}
}
